const router = require('koa-router')() //路由插件
const opt = require('./../util/operate') //工具方法 mongoose
// const Util = require('./../util/tool') // 工具方法
const Card = require('./../util/card') //会员卡表
const Subject = require('./../util/subject') //课程表
const ClockIn = require('./../util/clockin') //签到表



let natatorium = require('./natatorium/natatorium.js') //场馆
let team = require('./team/team.js') //教练
let user = require('./user/user.js') //用户
let order = require('./order/order.js') //订单操作
let administrator = require('./administrator/index.js') //管理员

natatorium(router, opt)
team(router, opt)
user(router, opt)
order(router, opt)
administrator(router, opt)

router.get('/', async(ctx, next) => {
  
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })

})


router.post('/test', async(ctx, next) => {
  let {body} = ctx.request
  opt.insert(Card, body)
  .then(res=>{
    console.log('res', res);
  }, err=>{
    console.log('err', err);
  })
  console.log('body', body);
  await ctx.render('index', {
    title: 'test'
  })

})

router.get('/string', async(ctx, next) => {
    ctx.body = 'koa2 string';
  })

// 打卡接口
router.post('/clockIn', async (ctx, next) => {
    let {body} = ctx.request;
    var result = await opt.find(Card, {_id: body._id})
    var tempData = null

    if(result.goodsType == 'vipcard') { //会员卡
      //计次卡规则
      if(!result.lastTime && result.count > 0) {
        result.count -= 1;
        //假如次数达到限制
        if(result.count == 0) {
          result.status = 300
        }
        // 更新会员卡数据
        opt.updata(Card, {
                _id: result._id,
              }, result)
        .then(result => {
          console.log('更新会员卡数据成功')
        }, err => {
          console.log('更新会员卡数据失败')
        })
      } else {
        var now = new Date().getTime()

        if(result.lastTime < now) {
          result.status = 300
        }
      }

      let {goodsNameAll,
        goodsName,
        natatorium,
        natatoriumId,
        openId,
        goodsType,
        out_trade_no,
        status,
        count,
        nonce_str,
        lastTime} = result
       
        
      // 添加打卡数据
      create = await  opt.create(ClockIn, 
        {goodsNameAll,
        goodsName,
        natatorium,
        natatoriumId,
        openId,
        goodsType,
        out_trade_no,
        status,
        count,
        nonce_str,
        lastTime,
        clockIn: new Date().getTime()
      }) 
      
      tempData = !!create._id == true ? 'ok' : 'err'

    }
    ctx.body = tempData
      
  })


module.exports = router




